package com.cn.yugan.Activity;

import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;

import com.cn.yugan.Engine.Adapter.ChatMsgViewAdapter;
import com.cn.yugan.Engine.Beans.MessageBeans;
import com.cn.yugan.Engine.Http.AddReqCookie;
import com.cn.yugan.Engine.Json.MessageJsonObj;
import com.cn.yugan.Utils.GsonUtils;
import com.cn.yugan.Utils.ToastUtils;
import com.cn.yugan.mobile.R;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;

import org.apache.http.Header;

import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class InnerChatMessageActivity extends AppCompatActivity implements View.OnClickListener {
    private ActionBar actionbar;


    private Button mBtnSend;// 发送btn  
    private Button mBtnBack;// 返回btn  
    private EditText mEditTextContent;
    private ListView mListView;
    private ChatMsgViewAdapter mAdapter;// 消息视图的Adapter  
    private List<MessageBeans> mDataArrays;// 消息对

    private String username = "";
    Handler mhandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 0:
                    mAdapter = new ChatMsgViewAdapter(InnerChatMessageActivity.this, mDataArrays,username);
                    mListView.setAdapter(mAdapter);
                    mListView.setSelection(mAdapter.getCount() - 1);
                    break;
                case 1:
                    break;
            }
            super.handleMessage(msg);
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_inner_chat_message);
        initIntent();
        initactionbar();
        initview();
        initdata();
    }

    private void initIntent() {
        Intent intent = getIntent();
        username = intent.getStringExtra("username");
    }

    //    //数据模拟
//    private String[] msgArray = new String[] { "有大吗", "有！你呢？", "我也有", "那上吧",
//            "打啊！你放大啊！", "你TM咋不放大呢？留大抢人头啊？CAO！你个菜B", "2B不解释", "尼滚...",
//            "今晚去网吧包夜吧？", "有毛片吗？", "种子一大堆啊~还怕没片？", "OK,搞起！！" };
//
//    private String[] dataArray = new String[] { "2012-09-22 18:00:02",
//            "2012-09-22 18:10:22", "2012-09-22 18:11:24",
//            "2012-09-22 18:20:23", "2012-09-22 18:30:31",
//            "2012-09-22 18:35:37", "2012-09-22 18:40:13",
//            "2012-09-22 18:50:26", "2012-09-22 18:52:57",
//            "2012-09-22 18:55:11", "2012-09-22 18:56:45",
//            "2012-09-22 18:57:33", };
//    private final static int COUNT = 12;// 初始化数组总数  
    //分隔符
    private void initdata() {
        AsyncHttpClient AsyncHttpClient = new AsyncHttpClient(true, 80, 443);
        AsyncHttpClient.addHeader("cookie", AddReqCookie.getNormalheader(this));
        RequestParams params = new RequestParams();
        params.put("username", username);
        AsyncHttpClient.post(this, getString(R.string.serverurl) + getString(R.string.getmessage), params, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int i, Header[] headers, byte[] bytes) {
                try {
                    String s = new String(bytes, "utf-8");
                    MessageJsonObj obj = GsonUtils.GsonToBean(s, MessageJsonObj.class);
                    if (obj.isSuccess()) {
                        mDataArrays = obj.getData();
                        mhandler.sendEmptyMessage(0);
                    } else {
                        ToastUtils.show(InnerChatMessageActivity.this, "数据错误");
                    }
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(int i, Header[] headers, byte[] bytes, Throwable throwable) {

            }
        });
    }

    private void initview() {
        mListView = (ListView) findViewById(R.id.inner_message_lv);
        mBtnSend = (Button) findViewById(R.id.inner_message_bt_send);
        mBtnSend.setOnClickListener(this);
        mEditTextContent = (EditText) findViewById(R.id.inner_message_et_message);
    }

    private void initactionbar() {
        actionbar = getSupportActionBar();
        actionbar.setTitle("与 " + username + " 私信");
        actionbar.setDisplayHomeAsUpEnabled(true);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            finish();
        }
        return true;
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.inner_message_bt_send) {
            String contString = mEditTextContent.getText().toString();
            if (contString.length() > 0) {
                MessageBeans entity = new MessageBeans();
                entity.setTitle("必败");
                entity.setTime(getDate());
                entity.setContent(contString);
                entity.setIsend(true);

                mDataArrays.add(entity);
                mAdapter.notifyDataSetChanged();// 通知ListView，数据已发生改变  

                mEditTextContent.setText("");// 清空编辑框数据  

                mListView.setSelection(mListView.getCount() - 1);// 发送一条消息时，ListView显示选择最后一项  
            }
        }
    }

    private String getDate() {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        return format.format(new Date());
    }
}
